

var ajax = require("../ajax/ajax");
var mongo = require("../mongo/mongo");

var validator = require("validator");
var moment = require("moment");
var py = require("../comm/py");
var mongoose = require('mongoose');
const task = require('../dict/task');
const yz = require('../comm/yz');
const fFlow = require('../flow/fFlow');
var rong = require('../comm/rong');
const dTask = require('../dict/task');


exports.saveTask = async function (task) {
    // body...
    task = dTask.fmtTask(task)


    var customerOrder = await mongo.findOneAsync({

        data: {

            _id: task.customerOrderId
        },
        collection: "customerOrder"

    });




    switch (task.taskClassId) {
        case "100":
            customerOrder[task.flowClassId].t100 = task.detail
            break;
        case "200":
            if (!yz.isArray(task.detail)) {
                throw '合计费用必须要有!'
            }
            if (!yz.isArray(task.detail2)) {
                throw '单件费用必须要有!'
            }
            customerOrder[task.flowClassId].t200 = {};

            customerOrder[task.flowClassId].t200.detail = task.detail
            customerOrder[task.flowClassId].t200.detail2 = task.detail2
            break;
        case "300":
            customerOrder[task.flowClassId].t300 = task.detail
            customerOrder[task.flowClassId].defaultSizeId = yz.IsNullThen(task.defaultSizeId, "")
            break;
        case "400":
            customerOrder[task.flowClassId].t400 = task.detail
            break;
        case "500":
        case "600":
        case "700":
        case "800":
            var colorData = customerOrder[task.flowClassId].data;
            colorData.forEach(function (color) {


                color.sizeArray.forEach(function (size) {

                    task.detail.forEach(function (item) {

                        if (item.colorName == color.colorName && item.sizeId == size.id) {

                            //找出data 下面 color 和size相同的节点
                            switch (task.taskClassId) {
                                case "500":  //裁片
                                    size.sectionDoneNum = yz.IsNullThen(item.sectionDoneNum, 0)
                                    break;
                                case "600":  //车缝
                                    size.sewDoneNum = yz.IsNullThen(item.sewDoneNum, 0)
                                    break;

                                case "700":  //后道
                                    size.completeDoneNum = yz.IsNullThen(item.completeDoneNum, 0)

                                    size.clothesDoneNum = size.completeDoneNum   //暂时成衣数量等于后道数量
                                    break;

                                case "800":  //交货
                                    size.cdeliverDoneNum = yz.IsNullThen(item.cdeliverDoneNum, 0)  //交货数量
                                    break;


                            }
                        }

                    }, this);

                }, this);



            }, this);




            break;
        case "900":
            customerOrder[task.flowClassId].t900 = task.detail

            break;
        default:
            break;
    }

    var re2 = await mongo.updateAsync({ _id: mongoose.Types.ObjectId(task.customerOrderId) }, {
        $set: {

            [task.flowClassId]: customerOrder[task.flowClassId]
        }
    }, "customerOrder")




    var upSet = {
        $set: {

            detail: task.detail,
            changeTime: new Date()
        }
    }
    switch (task.taskClassId) {
        case "200":
            upSet.$set.detail2 = task.detail2
            break;
        case "300":
            upSet.$set.defaultSizeId = task.defaultSizeId
            break;

    }



    var re = await mongo.updateAsync({ _id: mongoose.Types.ObjectId(task._id) }, upSet, "task")


    return


};


exports.changeMemberMsg = async function (o) {
    // body...
    var taskRole = ""
    var changeTypeStr = ""
    switch (o.memberType) {
        case "members":    //从负责人中减去
            taskRole = '参与人'
            break;
        case "managers":   //负责人
            taskRole = "负责人"
            break;
        default:
            break;

    }
    var msg = ""
    switch (o.changeType) {
        case "del":
            changeTypeStr = '删除'
            msg = "您在任务[" + o.taskName + "]中的[" + taskRole + "]身份被取消"
            break;
        case "add":
            changeTypeStr = '加入'
            msg = "您已经成为任务[" + o.taskName + "]中的[" + taskRole + "]"

            break;
        default:
            break;
    }

    var re = await rong.sendMsg({
        content: msg,
        extra: {
            event: "countMe"
        },
        toUserId: o.memberId
    },
        {
            noLog: true

        })



};

//接受任务
exports.acceptTask = function (taskId, expEndTime) {

    return new Promise(async (resolve, reject) => {


        var err = null;

        var info = await mongo.findOneAsync({
            data: {
                _id: taskId
            },
            db: "uzor",
            collection: "task"
        });

        if (info.statusId >= 200) {

            err = "任务已经接受, 无需再次接受";

        }
        else {


            var updateFind = {

                _id: mongoose.Types.ObjectId(taskId)
            }
            var updateSet = {
                $set: { statusId: 200, startTime: new Date(), expEndTime: new Date(expEndTime) }
            }
            var re = await mongo.updateAsync(updateFind, updateSet, "task", "uzor")  //改变任务状态




            updateFind = { _id: mongoose.Types.ObjectId(info.customerOrderId) };
            updateFind["flow." + info.flowClassId + ".nodeList.id"] = info.nodeId;
            updateSet = {
                $set: {
                }
            }; //修改此节点状态为300 
            updateSet.$set["flow." + info.flowClassId + ".nodeList.$.jd"] = 50     //修改任务进度到节点

            re = await mongo.updateAsync(updateFind, updateSet, "customerOrder")


            resolve(re)

        }
        resolve({ err: err, val: "ok" })


    });

};
//完成任务
exports.doneTask = function (taskId) {

    return new Promise(async (resolve, reject) => {



        var err = null;

        var info = await mongo.findOneAsync({
            data: {
                _id: taskId
            },
            db: "uzor",
            collection: "task"
        });

        if (info.statusId != 200) {



            err = "只能针对接受的任务进行完成操作, 本任务当前状态为[" + info.statusId + "]";

        }
        else {


            var updateFind = {

                _id: mongoose.Types.ObjectId(taskId)
            }
            var updateSet = {
                $set: { statusId: 300 }
            }


            if (info.customerOrderId) {

                //如果有订单编号
                if (!info.nodeId) {
                    throw "没有nodeId"
                }

                if (!info.flowClassId) {

                    throw "没有flowClassId!"
                }
                var customerOrder = await mongo.findOneAsync({
                    data: {

                        _id: info.customerOrderId
                    },
                    db: "uzor",
                    collection: "customerOrder"

                })
                switch (info.taskClassId) {
                    case "900":
                        if (!customerOrder.contractInfo) {
                            reject('没有维护合同信息!')
                            return

                        }
                        else {
                            //已经维护了合同信息

                            await mongo.upAsync({
                                _id: mongoose.Types.ObjectId(customerOrder.contractInfo._id)
                            }, {
                                    $set: {
                                        statusId: 100   //完成了结算任务, 那就让这个合同状态改为等待结算
                                    }
                                }, {
                                    collection: "contract"
                                })
                            await mongo.upAsync({
                                _id: mongoose.Types.ObjectId(customerOrder._id)
                            }, {
                                    $set: {
                                        statusId: 100   //完成了结算任务, 那就让这个订单状态改为等待结算
                                    }
                                }, {
                                    collection: "customerOrder"
                                })

                        }

                        break;

                    default:
                        break;
                }
                var nodeList = customerOrder.flow[info.flowClassId].nodeList
                var node = {};
                nodeList.forEach(function (element) {
                    if (element.id == info.nodeId) {
                        node = element
                        return false
                    }
                }, this);





                nodeList.forEach(function (element) {

                    var rely = yz.IsNullThen(element.rely, [])
                    rely.forEach(async function (relyNodeId) {
                        if (relyNodeId == info.nodeId) {
                            //如果依赖当前的节点


                            var re = await fFlow.exeNode(info.customerOrderId, info.flowClassId, element.id)



                        }
                    }, this);
                }, this);

            }


            //验证任务是否可以完成








            var re = await mongo.updateAsync(updateFind, updateSet, "task")



            //开始修改节点状态
            updateFind = { _id: mongoose.Types.ObjectId(info.customerOrderId) };

            updateFind["flow." + info.flowClassId + ".nodeList.id"] = info.nodeId;
            updateSet = {
                $set: {


                }
            }; //修改此节点状态为300 
            updateSet.$set["flow." + info.flowClassId + ".nodeList.$.statusId"] = 200
            updateSet.$set["flow." + info.flowClassId + ".nodeList.$.jd"] = 100
            re = await mongo.updateAsync(updateFind, updateSet, "customerOrder")
            //数据操作
            var itemArray = Object.assign(info.managers, info.members)

            var toUserIdArray = [];
            itemArray.forEach(function (item) {
                toUserIdArray.push(item._id)
            }, this);

            re - await mongo.updateAsync({
                _id: mongoose.Types.ObjectId(taskId)
            }, {
                    $set: { statusId: 300, endTime: new Date() }

                }, "task")



            re = await rong.sendMsg({
                content: "任务已完成!",
                extra: {
                    event: "countMe",
                    type: "success"
                },
                toUserId: toUserIdArray
            },
                {
                    noLog: true

                })

        }
        resolve({ err: err, val: "ok" })
    });
};

